<?php

namespace App\Http\Controllers;

use App\Jobs\PostViewsIncrement;
use App\Repos\PostRepo;
use Illuminate\Http\Request;
use App\Models\Post;
use Illuminate\Support\Facades\Redis;
class PostController extends Controller
{
    protected PostRepo $postRepo;

    public function __construct(PostRepo $postRepo)
    {
        $this->postRepo = $postRepo;
    }

    /**
     * @param Post $post
     * 热门浏览文章排行榜功能实现
        维护基于文章浏览数的有序集合
     */
//    public function show(Post $post)
//    {
//
//        $post->increment('views');
//        if($post->save()){
//            // 将当前文章浏览数 +1，存储到对应 Sorted Set 的 score 字段
//            Redis::zincrby('popular_posts',1,$post->id);
//        }
//
//        return 'Show Post #' . $post->id;
//    }

        //浏览文章
    public function show($id)
    {
        $post = $this->postRepo->getById($id);
//        $views = $this->postRepo->addViews($post);
        //分发队列任务
        $this->dispatch(new PostViewsIncrement($post));
        return "Show Post #{$post->id},views:{$post->views}";


    }


    //热门文章获取
//    public function popular()
//    {
//        $postIds = Redis::zrevrange('popular_posts',0,9);
//        if($postIds){
//            $idsStr = implode(',',$postIds);
//            $posts = Post::whereIn('id',$postIds)
//                ->select(['id','title','views'])
//                ->orderByRaw('field(`id`, ' . $idsStr . ')')
//                ->get();
//        }else{
//            $posts = null;
//        }
//        dd($posts->toArray());
//    }

        public function popular()
        {
            $posts = $this->postRepo->trending(10);

            if($posts){
                dump($posts->toArray());
            }
        }


        public function demo()
        {
            $url = route('demo1');
            dd($url);
        }
}
